<?
class NoBusinessBase_Merchant_Gateway_PayPal extends NoBusinessBase_Merchant_Gateway_Abstract
{

   protected $_API_Endpoint      = 'https://api-3t.sandbox.paypal.com/nvp';
   protected $_API_UserName      = 'platfo_1255077030_biz_api1.gmail.com';
   protected $_API_Password      = '1255077037';
   protected $_API_Signature     = 'Abg0gYcQyxQvnf2HDJkKtA-p6pqhA1k-KTYE0Gcy1diujFio4io5Vqjf';
   protected $_AUTH_token        = '';
   protected $_AUTH_signature    = '';
   protected $_AUTH_timestamp    = '';
   protected $_AuthMode          = '3TOKEN';
   protected $_subject           = '';
   protected $_version           = '65.1';

   protected $_paymentType       = "Sale";
   
   public $_doDirectPaymentResult;
   public function __construct($total, $formInfo)
   {
      parent::__construct($total, $formInfo);
   }

   public function setPaymentType($rhs)         { $this->_paymentType = $rhs; }
   
   public function executePayment()
   {
      /* Construct the request string that will be sent to PayPal.
         The variable $nvpstr contains all the variables and is a
         name value pair string with & as a delimiter */
      $nvpstr=
         "&PAYMENTACTION="    . urlencode($this->_paymentType).
         "&AMT="              . urlencode($this->_amount).
         "&CREDITCARDTYPE="   . urlencode($this->_creditCardType).
         "&ACCT="             . urlencode($this->_creditCardNumber).
         "&EXPDATE="          . $this->_expDateMonth.$this->_expDateYear.
         "&CVV2="             . urlencode($this->_cvv2Number).
         "&FIRSTNAME="        . urlencode($this->_firstName).
         "&LASTNAME="         . urlencode($this->_lastName).
         "&STREET="           . urlencode($this->_address1).
         "&CITY="             . urlencode($this->_city).
         "&STATE="            . urlencode($this->_state).
         "&ZIP="              . urlencode($this->_zip).
         "&COUNTRYCODE="      . "US".
         "&CURRENCYCODE="     . urlencode($this->_currencyCode);

      //print_r(explode("&", $nvpstr));

      /* Make the API call to PayPal, using API signature.
         The API response is stored in an associative array called $resArray */
      $this->_doDirectPaymentResult = $this->_hashCall("doDirectPayment",$nvpstr);
      return $this->_doDirectPaymentResult;
   }

   public function parseDate($expDate)
   {
      if(!parent::parseDate($expDate))
         return false;

      // Month must be padded with leading zero
      $this->_expDateMonth = str_pad($this->_expDateMonth, 2, '0', STR_PAD_LEFT);
      return true;
   }

   /**
   * hashCall: Function to perform the API call to PayPal using API signature
   * @methodName is name of API  method.
   * @nvpStr is nvp string.
   * returns an associtive array containing the response from the server.
   */
   protected  function _hashCall($methodName,$nvpStr)
   {
      // form header string
      $nvpheader=$this->_nvpHeader();
      
      //setting the curl parameters.
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL,$this->_API_Endpoint);
      curl_setopt($ch, CURLOPT_VERBOSE, 1);

      //turning off the server and peer verification(TrustManager Concept).
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

      curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
      curl_setopt($ch, CURLOPT_POST, 1);

      //in case of permission APIs send headers as HTTPheders
      if(!empty($this->_AUTH_token) && !empty($this->_AUTH_signature) && !empty($this->_AUTH_timestamp))
      {
         $headers_array[] = "X-PP-AUTHORIZATION: ".$nvpheader;

         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_array);
         curl_setopt($ch, CURLOPT_HEADER, false);
      }
      else
      {
         $nvpStr=$nvpheader.$nvpStr;
      }  
      //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
      //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
      //if(USE_PROXY)
      //   curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);
   
      //check if version is included in $nvpStr else include the version.
      if(strlen(str_replace('VERSION=', '', strtoupper($nvpStr))) == strlen($nvpStr))
      {
         $nvpStr = "&VERSION=" . urlencode($this->_version) . $nvpStr;
      }

      $nvpreq="METHOD=".urlencode($methodName).$nvpStr;

      //setting the nvpreq as POST FIELD to curl
      curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);

      //getting response from server
      $response = curl_exec($ch);

      //convrting NVPResponse to an Associative Array
      $nvpResArray=$this->_deformatNVP($response);
      $nvpReqArray=$this->_deformatNVP($nvpreq);

      if(curl_errno($ch))
      {
         // moving to display page to display curl errors
         $flashMsg = Zend_Controller_Action_HelperBroker::getStaticHelper('flashMessenger');
         $flashMsg->addMessage(curl_error($ch));
         return false;
      }
      else
      {
         //closing the curl
         curl_close($ch);
      }
      return $nvpResArray;
   }

   protected function _nvpHeader()
   {
      $nvpHeaderStr = "";
      switch($this->_AuthMode)
      {
         case "3TOKEN" :
         $nvpHeaderStr = "&PWD=".urlencode($this->_API_Password)."&USER=".urlencode($this->_API_UserName)."&SIGNATURE=".urlencode($this->_API_Signature);
         break;
         
         case "FIRSTPARTY" :
         $nvpHeaderStr = "&SUBJECT=".urlencode($this->_subject);
         break;
         
         case "THIRDPARTY" :
         $nvpHeaderStr = "&PWD=".urlencode($this->_API_Password)."&USER=".urlencode($this->_API_UserName)."&SIGNATURE=".urlencode($this->_API_Signature)."&SUBJECT=".urlencode($this->_subject);
         break;
         
         case "PERMISSION" :
         $nvpHeaderStr = $this->_formAutorization($this->_AUTH_token,$this->_AUTH_signature,$this->_AUTH_timestamp);
         break;
      }
      return $nvpHeaderStr;
   }

   /** This function will take NVPString and convert it to an Associative Array and it will decode the response.
   * It is usefull to search for a particular key and displaying arrays.
   * @nvpstr is NVPString.
   * @nvpArray is Associative Array.
   */

   protected function _deformatNVP($nvpstr)
   {

      $intial=0;
      $nvpArray = array();
      while(strlen($nvpstr))
      {
         //postion of Key
         $keypos= strpos($nvpstr,'=');
         //position of value
         $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);

         /*getting the Key and Value values and storing in a Associative Array*/
         $keyval=substr($nvpstr,$intial,$keypos);
         $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
         //decoding the respose
         $nvpArray[urldecode($keyval)] =urldecode( $valval);
         $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
      }
      return $nvpArray;
   }

   protected function _formAutorization($auth_token,$auth_signature,$auth_timestamp)
   {
      $authString="token=".$auth_token.",signature=".$auth_signature.",timestamp=".$auth_timestamp ;
      return $authString;
   }
}
